package com.chukun.flink.stream.window.process.windows;

import com.chukun.flink.stream.window.process.accumulator.AverageAccumulator;
import com.chukun.flink.stream.window.process.function.AverageAggregation;
import com.chukun.flink.stream.window.source.SourceForWindow;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * @author chukun
 * @version 1.0.0
 * @description Aggregation 窗口函数
 * @createTime 2022年05月22日 23:50:00
 */
public class WindowAggregationOperator {

    public static void main(String[] args) throws Exception {

        // 创建运行环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 添加数据源
        DataStream<Tuple3<String, Integer, String>> stremSource = env.addSource(new SourceForWindow(1000, false));

        // 根据数据流中的元素f0字段作为作为key对数据流分组
        DataStream<AverageAccumulator> aggregate = stremSource.keyBy((key) -> key.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                // 对窗口应用 AggregateFunction 窗口函数
                .aggregate(new AverageAggregation());


        aggregate.print("窗口-aggregate计算: ");

        env.execute("WindowAggregationOperator");
    }
}
